<template>
  <view class="table-wrap">
    <slot name="tableFilter" :columns="filterCols"></slot>

    <view class="table-handler">
      <slot name="tableHandler" :checked="checkedData" :columns="columns"></slot>
      <button class="margin-right-lg button light" v-for="btn in gridButtons" @click="onGridButton(btn)">
        <text class="cuIcon-roundaddfill add-icon" v-if="btn.servcie_type==='add'"></text>
        <text> {{btn.button_name}}</text>
      </button>
      <slot name="tableHandlerRight" :checked="checkedData" :columns="columns"></slot>
    </view>
    <view class="table-container ">
      <table-list :cell-header-style="setCellStyle" ref="tableRef" :show-header="true" row-key="id" :columns="columns"
        :stripe="true" :fit="false" @rowClick="rowClick" @toggleRowSelection="toggleRowSelection"
        @toggleAllSelection="toggleAllSelection" :border="true" @edit="buttonEdit" @dele="dele" @detail="toDetail"
        @on-button="onRowButton" :data="list">
      </table-list>
    </view>
    <view class="table-footer">
      <uni-pagination title=" " show-icon="false" :total="total" :pageSize="rownumber" :current="pageNo"
        @change="changePage"></uni-pagination>
    </view>
    <!--    <movable-area style="width:100%;height: 20rem;">
    				<movable-view direction="horizontal"> <view class="" style="height: 10rem;background-color: #333;width: 10rem;">111</view></movable-view>
    			</movable-area> -->
  </view>
</template>

<script>
  export default {
    name: "table-content",
    props: {
      service: {
        type: String,
        default: ''
      },
      deleteService: {
        type: String,
        default: ''
      },
      addService: {
        type: String,
        default: ''
      },
      updateService: {
        type: String,
        default: ''
      },
      app: {
        type: String,
        default: ''
      },
      includeColumns: {
        type: Array
      },
      colWidth: {
        type: Number,
        default: 20
      },
      defaultCondition: {
        type: Array
      },
      filterData: {
        type: Object
      }
    },
    computed: {
      columns() {
        let columns = this.colV2?._fieldInfo
        let res = []
        if (Array.isArray(columns) && columns.length > 0) {
          const colMap = columns.reduce((pre, cur) => {
            pre[cur.column] = cur;
            return pre
          }, {})
          if (Array.isArray(this.includeColumns) && this.includeColumns.length > 0) {
            this.includeColumns.forEach(col => {
              if (colMap[col]) {
                let item = colMap[col]
                item.name = item.column
                item.width = this.colWidth
                res.push(item)
              }
            })
          } else {
            columns.forEach(item => {
              if (Array.isArray(item?.options) && item?.options.length > 0) {
                item.options = item?.options.map(e => {
                  e.text = e.label;
                  return e
                })
              }
              item.name = item.column
              item.width = this.colWidth
              res.push(item)
            })
          }
          if (res.length > 0) {
            res[0].fixed = true
          }
          res.unshift({
            type: 'selection',
            fixed: true,
            width: 10,
            height: 10
          })
        }

        if (Array.isArray(this.rowButtons) && this.rowButtons.length > 0) {
          res.push({
            name: 'operation',
            type: 'operation',
            label: '操作',
            width: 20,
            fixed: true,
            renders: this.rowButtons.filter(item => ['edit', 'delete'].includes(item.button_type)),
            // [{
            //     name: '编辑',
            //     func: 'edit' // func 代表子元素点击的事件 父元素接收的事件 父元素 @edit
            //   },
            //   {
            //     name: '详情',
            //     func: 'detail' // func 代表子元素点击的事件 父元素接收的事件 父元素 @edit
            //   },
            //   {
            //     name: '删除',
            //     type: 'warn',
            //     func: "dele"
            //   },
            // ]
          })
        }
        return res
      },
      rowButtons() {
        return this.colV2?.rowButton?.filter(item => !["duplicatedeep", "duplicate"].includes(item.button_type))?.map(
          item => {
            item.name = item.button_name
            item.func = item.button_type
            if (item.button_type && item.button_type.indexOf('delete') !== -1) {
              item.type = 'warn'
              item.func = 'dele'
            }
            if (item.button_type && item.button_type.indexOf('detail') !== -1) {
              item.type = ''
              item.func = 'detail'
            }
            return item
          })
      },
      gridButtons() {
        return this.colV2?.gridButton?.filter(item => item.client_type && item.client_type.indexOf('APP') !== -1 && ![
          'export', 'import', 'select', 'refresh', 'delete', 'batch_delete'
        ].includes(item.button_type))
      },
    },
    created() {
      this.getV2().then(_ => {
        this.getList()
        this.setFilterCols()
      })
    },
    data() {
      return {
        colV2: null,
        list: [],
        pageNo: 1,
        total: 0,
        rownumber: 5,
        checkedData: [],
        filterCols: []
      };
    },
    methods: {
      clearCheck() {
        this.checkedData = []
        this.$refs?.tableRef?.clearCheck()
      },
      setCellStyle() {
        return {
          background: '$retail-color-dark'
        }
      },
      setFilterCols() {
        const includeColumns = ['goods_name', 'sale_state']
        // const includeColumns = ['supplier_name', 'brand_name', 'goods_name', 'sale_state']
        if (Array.isArray(this.columns)) {
          this.filterCols = this.colV2?._fieldInfo.filter(item => includeColumns.includes(item.column)).map(item => {
            if (item.column === 'sale_state') {
              item._subtype = 'select'
              item.value = '全部'
            } else {
              item.placeholder = '请输入商品名称/商品条码'
              item._searchCol = 'goods_barcode,goods_name,mnemonic_code'
            }
            return item
          })
        }
      },
      changePage(e) {
        const {
          type,
          current
        } = e
        this.pageNo = current
        this.onFilter(null, current)
        // this.getList()
      },
      onFilter(data = {}, pageNo) {
        const conditions = []
        const relationConditions = {
          relation: "OR",
          data: []
        }
        if (this.filterData && Object.keys(this.filterData).length > 0) {
          data = this.filterData
        }
        this.pageNo = pageNo || 1
        this.columns.forEach(col => {
          if (data && data[col.column]) {
            if (col?._searchCol && col?._searchCol.split(',').length > 0) {
              col._searchCol.split(',').forEach(colName => {
                relationConditions.data.push({
                  colName: colName,
                  ruleType: 'like',
                  value: data[col.column]
                })
              })
            } else {
              conditions.push({
                colName: col.column,
                ruleType: 'like',
                value: data[col.column]
              })
            }

          }
        })
        this.getList(conditions, relationConditions)
      },
      onRowButton(e, data, dataIndex) {
        switch (e.button_type) {
          case 'edit':
            this.buttonEdit(data)
            break;
          case 'delete':
            if (data?.id) {
              this.$emit('delete', data.id)
            }
            break;
          case 'detail':
            this.toDetail(data)
            break;
        }
      },
      refresh() {
        this.pageNo = 1
        this.total = 0
        this.getList()
      },
      onGridButton(e) {
        console.log(e);
        switch (e.button_type) {
          case 'refresh':
            this.refresh()
            break;
          case 'add':
            const url = `/pages/public/form/form?serviceName=${this.service}&type=add`
            uni.navigateTo({
              url
            })
            break;
          case 'batch_delete':
            if (Array.isArray(this.checkedData)) {
              if (this.checkedData.length > 0) {
                this.$emit('delete', this.checkedData.map(item => item.id).toString())
              } else {
                uni.showModal({
                  title: '提示',
                  content: '请选择您要删除的数据',
                  showCancel: false
                })
              }
            }
            break;
          case "customize":
            if (e.operate_type === 'URL跳转' && e.more_config) {
              let moreConfig = JSON.parse(e.more_config)
              if (moreConfig?.navUrl) {
                uni.navigateTo({
                  url: moreConfig?.navUrl
                })
              }
            } else if (e.operate_type === '操作') {
              if (e.operate_mode === '静默操作') {
                this.handlerCustomButton(e)
              }
            }
            break;
          default:
            break;
        }
      },
      async handlerCustomButton(e) {
        if (e?.operate_params) {
          try {
            const operate_params = JSON.parse(e.operate_params)
            const operate_service = e.operate_service
            console.log(e.pre_data_handle);
            console.log(operate_params);
            const rowDatas = this.deepClone(this.checkedData);
            console.log(rowDatas);
            if (rowDatas.length > 0) {
              const rowData = rowDatas[0]
              if (e.pre_data_handle) {
                eval(`(${e.pre_data_handle})(rowDatas)`)
                console.log(rowDatas);
              }
              if (Array.isArray(operate_params?.condition) && operate_params.condition
                .length > 0) {
                operate_params.condition.forEach(cond => {
                  if (typeof cond.value === 'object' && cond.value.value_type === 'rowData') {
                    cond.value = rowData[cond.value.value_key];
                  } else if (typeof cond.value === 'object' && cond.value.value_type ===
                    'constant') {
                    cond.value = cond.value.value;
                  }
                });
              }

              if (Array.isArray(operate_params?.data) && operate_params.data.length >
                0) {
                operate_params.data.forEach(data => {
                  if (typeof data === 'object') {
                    Object.keys(data).forEach(key => {
                      if (typeof data[key] === 'object' && data[key].value_type ===
                        'rowData') {
                        data[key] = rowData[data[key].value_key];
                      } else if (typeof data[key] === 'object' && data[key]
                        .value_type === 'constant') {
                        data[key] = data[key].value;
                      }
                    });
                  }
                });
              }
              console.log(operate_params);
              let req = [{
                serviceName: e.operate_service,
                condition: operate_params.condition || [{
                  colName: 'id',
                  ruleType: 'in',
                  value: rowDatas.map(item => item.id).toString()
                }],
                data: operate_params.data
              }];
              const url =
                `/${e.application||uni.getStorageSync('activeApp')}/${e.servcie_type||'operate'}/${e.operate_service}`
              const res = await this.$http.post(url, req)
              if (res?.data?.resultMessage) {
                uni.showModal({
                  title: '提示',
                  content: res?.data?.resultMessage,
                  showCancel: false
                })
                this.clearCheck()
              }

            } else {
              uni.showModal({
                title: '提示',
                content: '请在列表左侧勾选要操作的数据',
                showCancel: false
              })
            }
          } catch (e) {
            //TODO handle the exception
          }
        }

      },
      dele(ite, index) {
        uni.showModal({
          title: '提示',
          content: '确认删除？',
          success: (res) => {
            if (res.confirm) {

            }
          }
        })
      },
      toDetail(e) {
        console.log(e);
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击详情'
        })
        uni.navigateTo({
          url: `/pages/public/form/form?serviceName=${this.service}&type=detail&id=${e.id}`
        })
      },
      buttonEdit(item, index) {
        // uni.showToast({
        //   icon: 'none',
        //   duration: 3000,
        //   title: '点击编辑'
        // })
        uni.navigateTo({
          url: `/pages/public/form/form?serviceName=${this.service}&type=update&id=${item.id}`
        })
      },
      toggleAllSelection(selected, array) {
        // 用于多选表格，切换所有行的选中状态 ，第一个参数代表选中状态，参数二代表选中的对象
        // uni.showToast({
        //   icon: 'none',
        //   duration: 3000,
        //   title: '点击全选'
        // })
        this.checkedData = array
        // console.log('全选', array)
      },
      rowClick() {},
      toggleRowSelection(selected, array) {
        // 用于多选表格，切换某一行的选中状态，第一个参数代表选中状态，参数二代表选中的对象
        // uni.showToast({
        //   icon: 'none',
        //   duration: 3000,
        //   title: '点击单选'
        // })
        this.checkedData = array
        // console.log('单选', array)
      },
      async getV2() {
        let app = this.app || uni.getStorageSync('activeApp');
        let colVs = await this.getServiceV2(this.service, 'list', 'list', app);
        if (colVs.srv_cols) {
          colVs.srv_cols = colVs.srv_cols.filter(item => item.in_list === 1 || item.in_list === 2);
        }

        if (Array.isArray(colVs?.rowButton) && colVs?.rowButton.length > 0) {
          colVs.rowButton = colVs.rowButton.map(item => {
            try {
              item.moreConfig = {}
              if (item.more_config) {
                item.moreConfig = JSON.parse(item.more_config)
              }
            } catch (e) {
              console.log('error,', e)
              //TODO handle the exception
            }
            return item
          })
        }
        console.log(colVs)
        this.colV2 = colVs;

        return colVs;
      },
      getList(cond, relationCond) {
        const url = `/${this.app}/select/${this.service}`;
        const req = {
          "serviceName": "srvretail_goods_info_select",
          "colNames": ["*"],
          "condition": [],
          "page": {
            "pageNo": this.pageNo,
            "rownumber": this.rownumber
          },
          "order": [],
        }
        if (cond) {
          req.condition = cond
        }
        if (relationCond) {
          req.relation_condition = relationCond
        }
        if (Array.isArray(this.defaultCondition) && this.defaultCondition.length > 0) {
          req.condition = [...req.condition, ...this.defaultCondition]
        }
        uni.showLoading({})
        this.$http.post(url, req).then(res => {
          if (res?.data?.state === 'SUCCESS') {
            this.list = res.data.data
          }
          if (res?.data?.page) {
            this.total = res.data.page.total
            this.pageNo = res.data.page.pageNo
          }
          uni.hideLoading()
        }).catch(_ => {
          uni.hideLoading()
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .table-wrap {
    height: 100%;
    display: flex;
    flex-direction: column;

    // .table-container {
    //   flex: 1;
    //   position: relative;

    //   ::v-deep .zb-table-scroll{
    //     position: relative;
    //     &::after {
    //     pointer-events: none;
    //     content: '';
    //     position: absolute;
    //     width: 10rem;
    //     height: 100%;
    //     right: 0;
    //     top: 0;

    //     background-image: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(0, 0, 0, 0.1));
    //     z-index: 9;
    //   }
    //   }
    // }

    .table-footer {
      padding: $retail-button-padding-base;

      ::v-deep .page--active {
        background-color: $retail-color-primary;
      }
    }
  }

  .table-handler {
    padding: 20px;
    display: flex;
    align-items: center;

    .table-button {
      display: inline-block;
      min-width: 80px;
      height: 40px;
      line-height: 40px;
      margin-right: 20px;
    }
  }
</style>
